package topic;

import com.rabbitmq.client.Channel;
import common.ContantsConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * Created by Will.Zhang on 2017/2/16 0016 17:08.
 */
public class TopicProducer {


    public static void main(String[] args) throws IOException, TimeoutException {

        String username = ContantsConfig.USER;
        String password = ContantsConfig.PASSWORD;

        String exchangeName = "alters";
        String routingKey = "critical.rate_limit";

        //端口默认使用5672
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(ContantsConfig.MQ_HOST);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);

        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(false);

        RabbitTemplate template = new RabbitTemplate(connectionFactory);
        template.setExchange(exchangeName);

        /*
        alters是一个topic类型的交换器
        这次发送的消息路由键是critical.rate_limit
        根据消费者绑定的规则
        路由键为critical.*和*.rate_limit的两个队列都能接收到这条消息
         */
        Message criticalMessage = MessageBuilder.withBody("路由键为critical.*和*.rate_limit的两个队列,都能接收到这个消息".getBytes())
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)
                .build();
        template.send(exchangeName, routingKey, criticalMessage);
        channel.close();
        connection.close();
    }
}
